package com.github.ybq.core.style;

import com.github.ybq.core.sprite.Sprite;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Rect;

public class PulseRing extends Sprite {
    private static String TAG = "PulseRing";
 

    private AnimatorValue mAnimatorValue;
    private float mRadiusValue = 0f;
    private float mAlpha = 1f;

    public PulseRing(){
        super();
        initAnimator();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setStyle(Paint.Style.STROKE_STYLE);
        mPaint.setStrokeWidth(getPaintStrokeWidth());
        if (getRect() != null){
            Rect bounds = clipSquare(getRect(),30);
            float maxRadius = bounds.getWidth() / 2f - getPaintStrokeWidth() * 2;
            mRadiusValue = mRadiusValue * maxRadius;
            mPaint.setAlpha(mAlpha);
            canvas.drawCircle(bounds.getCenterX(),bounds.getCenterY(),mRadiusValue,mPaint);
            startAnimator();
        }
    }
    @Override
    public void startAnimator(){
        if (mAnimatorValue != null){
            if (!mAnimatorValue.isRunning()){
                mAnimatorValue.start();
            }
        }
    }
    @Override
    public boolean isRunning() {
        if (mAnimatorValue != null){
            return mAnimatorValue.isRunning();
        }
        return super.isRunning();
    }
    private void initAnimator(){
        if (mAnimatorValue == null){
            mAnimatorValue = new AnimatorValue();
            mAnimatorValue.setLoopedCount(Animator.INFINITE);
            mAnimatorValue.setDuration(1000);
            mAnimatorValue.setCurveType(Animator.CurveType.OVERSHOOT);
            mAnimatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
                @Override
                public void onUpdate(AnimatorValue animatorValue, float v) {
                    mRadiusValue = v;
                    if(v >= 0.7f){
                        mAlpha = 0.7f;
                    }if (v >= 0.8f){
                        mAlpha = 0.5f;
                    }else if (v >= 0.9f){
                        mAlpha = 0f;
                    }else {
                        mAlpha = 1f;
                    }
                    if (getComponent() != null){
                        getComponent().invalidate();
                    }
                }
            });
        }
    }
    @Override
    public void stopAnimator(){
        if (mAnimatorValue != null){
            if (mAnimatorValue.isRunning()){
                mAnimatorValue.stop();
            }
        }
    }
}

